package com.aote.work;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.dbtools.DBTools;

/**
 * 工作
 * 
 */
public class Work {

	// 名字
	private String name = "";

	// 名字及sql
	private Map<String, Element> sqls = new HashMap<String, Element>();

	public Work(String name, Element config) {
		this.name = name;
		NodeList sqlsElem = config.getElementsByTagName("sql");
		for (int i = 0; i < sqlsElem.getLength(); i++) {
			Element sqlElem = (Element) sqlsElem;
			String sqlName = sqlElem.getAttribute("name");
			sqls.put(name, sqlElem);
		}
	}

	/**
	 * 工作任务数量
	 */
	public Map amount() {
		Map result = new HashMap();
		Iterator iter = sqls.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			Element sqlElem = (Element) this.sqls.get(key);
			int num = getAmount(sqlElem);
			result.put(key, num + "");
		}
		return result;
	}

	/**
	 * 得到工作任务数
	 */
	public int getAmount(Element sqlElem) {
		int result = 0;
		try {
			if (sqlElem.hasAttribute("amountsql")) {
				String sql = sqlElem.getAttribute("amountqsql");
				String[][] datas = DBTools.executeQueryWithTableHead(sql);
				String str = datas[1][0];
				result = Integer.parseInt(str);
			} else {
				String sql = sqlElem.getAttribute("datasql");
				String[][] datas = DBTools.executeQueryWithTableHead(sql);
				result = datas.length - 1;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;

	}

	/**
	 * 得到工作任务
	 */
	public Map getWork(int num) {
		int findNum = num;
		Map result = new HashMap();
		try {
			Iterator iter = sqls.keySet().iterator();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				Element sqlElem = (Element) this.sqls.get(key);
				String sql = sqlElem.getAttribute("datasql");
				String[][] datas = DBTools.executePageQueryWithTableHead(sql,
						0, num);
				List queryDatas = DBTools.arrayToHashtable(datas);
				result.put(key, queryDatas);
				if (queryDatas.size() == findNum) {
					break;
				}
				findNum = findNum - queryDatas.size();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;
	}

}
